import React, { Component } from "react";

 // 导入withRouter模块
 import { withRouter } from "react-router-dom";
 // 导入models模块
 import models from "@/models/common";
 // 导入Captcha
 import Captcha from "@/components/Captcha";
 
 // 导入antd用到的组件
 import { Form, Input, Button, Row, Col, message, Modal } from "antd";

const layout = {
  labelCol: {
    span: 6,
  },
  wrapperCol: {
    span: 18,
  },
};
const tailLayout = {
  wrapperCol: {
    offset: 8,
    span: 16,
  },
};

class MobileLogin extends Component {

// 初始化状态
state = {
	//注册按钮加载状态
	loading:false,
	// 模态框状态
	isModalVisible: false,
	// key
	key: "",
	// token
	token: "",
	// expire 有效期
	expire: 0,
	// 手机号
	mobile: "",
	// requestId
	requestId: "",
	// 倒计时
		number: 60,
		// 用于判断是否进入了倒计时
		can:true
  };

  render() {
    return (
		<div>
			<h1>短信登录:</h1>
			<Form
		   {...layout}
		   name="basic"
		   initialValues={{
			 remember: true,
		   }}
		   onFinish={this.onFinish}
		   onFinishFailed={this.onFinishFailed}
		 >
		   <Form.Item
			 label="手机号"
			 name="mobile"
			 rules={[
			   {
				 required: true,
				 message: "请输入您的手机号!",
			   },
			 ]}
		   >
			 <Input ref={(c) => (this.mobile = c)} />
		   </Form.Item>
 
		   <Form.Item label="验证码" extra="短信验证">
			 <Row gutter={8}>
			   <Col span={14}>
				 <Form.Item
				   name="code"
				   noStyle
				   rules={[
					 {
					   required: true,
					   message: "请输入短信验证码!",
					 },
				   ]}
				 >
				   <Input />
				 </Form.Item>
			   </Col>
			   <Col span={10}>
								 <Button onClick={this.showModal} block disabled={!this.state.can}>
								 {this.state.can ?'获取验证码':this.state.number}
								 </Button>
			   </Col>
			 </Row>
		   </Form.Item>
 
		   <Form.Item {...tailLayout}>
			 <Button type="primary" htmlType="submit" loading={this.state.loading}>
			   登录
			 </Button>
		   </Form.Item>
		 </Form>
 
		 <Modal
		   title="Basic Modal"
		   visible={this.state.isModalVisible}
		   onOk={this.handleOk}
		   onCancel={this.handleCancel}
		 >
		   <Form>
			 <Form.Item label="验证码">
			   <Row gutter={8}>
				 <Col span={14}>
				   <Form.Item
					 name="captcha"
					 noStyle
					 rules={[
					   {
						 required: true,
						 message: "请输入验证码!",
					   },
					 ]}
				   >
					 <Input ref={(c) => (this.getInp = c)} />
				   </Form.Item>
				 </Col>
				 <Col span={10}>
				   <Captcha
					 ref={(c) => (this.change = c)}
					 height="31.6px"
					 width="100px"
					 setKey={this.setKey}
				   />
				 </Col>
			   </Row>
			 </Form.Item>
		   </Form>
		 </Modal>
      </div>
    );
	}
	
	// 点击提交，并且有值的情况
	onFinish = (values) => {
		// 判断验证码是否过期
		if (this.state.expire - Date.now() / 1000 >= 0) {
		  values["requestId"] = this.state.requestId;
		  // 发送登录请求
		  models.mobileLogin(values).then((ret) => {
			if (ret.errNo === 0) {
			  // 登录成功
			  this.setState(()=>{
				return {
				  loading:true
				}
			  })
			  message.success(ret.message,2,()=>{
				  this.props.history.push("/home");
			  });
			  
			} else {
			  message.error(ret.message);
			}
		  });
		} else {
		  // 验证码过期
		  message.error("短信验证码过期，请重新获取");
		}
	  };
	
	  // 点击提交，没有值的情况
	  onFinishFailed = () => {
		message.error("请输入手机号和验证码");
	  };
	
	  // 倒计时
	  countDown = () => {
		if (this.state.number < 1) {
				this.setState(() => {
					return { number :60,can:true};
				});
		} else {
		  // 倒计时开始，
		  this.setState((state) => {
					return { number :state.number-1,can:false};
				});
		  setTimeout(() => {
			// console.log(this.state.number);
			this.countDown();
		  }, 1000);
		}
	  };
	
	  // 点击显示模态框
	  showModal = () => {
		// 在点击后，如果没有输入正确的手机号的话，则直接提示输入正确的手机号
		if (/^1[3-9]\d{9}$/.test(this.mobile.props.value)) {
		  this.setState(() => {
			return {
			  isModalVisible: true,
			  mobile: this.mobile.props.value,
			};
		  });
		} else {
		  message.error("请输入正确手机号");
		}
	  };
	
	  // 点击模态框中的确认
	  handleOk = () => {
		// 进行验证
		// 获取输入框的内容
		let captcha = this.getInp.props.value;
		// 合并好发送的数据
		let obj = {
		  key: this.state.key,
		  captcha,
		};
		// 发送验证码验证请求
		models.mobileVerify(obj).then((ret) => {
		  // 判断是否验证成功
		  if (ret.errNo === 0) {
			// 成功后，保存token，expire
			this.setState(
			  () => {
				return {
				  token: ret.context.token,
				  expire: ret.context.expire,
				};
			  },
			  // 这个是setState执行完毕后的回调函数，在此可进行验证码的发送
			  () => {
				message.success(ret.message);
				// 关闭模态框
				setTimeout(() => {
				  this.setState(() => {
					return {
					  isModalVisible: false,
					};
				  });
				  this.change.clickCode();
				}, 1000);
	
				// 发送短信验证码，并进入倒计时
				// 整合需要的数据
				let objSend = {
				  token: this.state.token,
				  mobile: this.state.mobile,
				  type: 0,
				};
	
				models.mobileSmsSend(objSend).then((ret) => {
				  if (ret.errNo === 0) {
					message.success("短信发送成功");
					// 短信发送成功
					message.success(ret.message);
					// 将requestId存在state中
									this.countDown();
					this.setState(() => {
					  return { requestId: ret.requestId };
					});
				  } else {
					// 验证失败，提示相应的信息
					message.error(ret.message);
				  }
				});
			  }
			);
		  } else {
			// 验证失败,需要刷新图片，并清空输入框
			this.change.clickCode();
			message.error(ret.message);
		  }
		});
	  };
	
	  // 点击模态框中的取消
	  handleCancel = () => {
		// 刷新图片
		this.change.clickCode();
		// 关闭模态框
		this.setState(() => {
		  return {
			isModalVisible: false,
		  };
		});
	  };
	
	  // 获取key
	  setKey = (key) => {
		// console.log(key);
		// 由于在验证验证码时需要使用key，在这进行保存
		this.setState(() => {
		  return {
			key,
		  };
		});
	  };
}

 export default withRouter(MobileLogin);
 